package com.gitee.linmt.evaluator;

import com.gitee.linmt.service.LocationServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 权限验证.
 *
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
    
    private final LocationServiceImpl locationService;
    
    public static final Logger LOGGER = LoggerFactory.getLogger(CustomPermissionEvaluator.class);
    
    public CustomPermissionEvaluator(final LocationServiceImpl locationService) {
        this.locationService = locationService;
    }
    
    @Override
    public boolean hasPermission(final Authentication authentication, final Object location, final Object permission) {
        LOGGER.info("authentication：{}", authentication);
        LOGGER.info("location：{}", location);
        LOGGER.info("permission：{}", permission);
        final boolean hasPermission = locationService.hasPermission(authentication.getName(), location.toString());
        LOGGER.info(String.format("%s 访问 location（%s），权限验证结果：%s", authentication.getName(), location.toString(),
                hasPermission));
        return hasPermission;
    }
    
    @Override
    public boolean hasPermission(final Authentication authentication, final Serializable targetId,
            final String targetType, final Object permission) {
        LOGGER.info("authentication：{}", authentication);
        LOGGER.info("targetId：{}", targetId);
        LOGGER.info("targetType：{}", targetType);
        LOGGER.info("permission：{}", permission);
        return false;
    }
    
}
